package com.zx.sercurity;

import android.content.Context;

import com.zx.sercurity.rootdetectorplus.RootDetectorPlus;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class RootAsyncRisk extends AsyncRiskControlAbs<ArrayList<String>> implements Runnable {

    private WeakReference<Context> contextWeakReference;
    private AsyncResultWrapper<ArrayList<String>> asyncResultWrapper = new AsyncResultWrapper<>(ProcessState.IDLE, false, riskType(), new ArrayList<>());

    public RootAsyncRisk(AsyncRiskListener listener) {
        super(listener);
    }

    @Override
    public RiskEnum riskType() {
        return RiskEnum.AsyncRootRisk;
    }

    @Override
    public void beginCheck(Context context) {
        contextWeakReference = new WeakReference<>(context);
        if (listener != null) {
            asyncResultWrapper = asyncResultWrapper.newState(ProcessState.RUNNING);
            listener.onAsyncRiskStateChange(asyncResultWrapper);
        }
        getService().schedule(this, 500, TimeUnit.MILLISECONDS);
    }


    @Override
    public void destroy() {
        contextWeakReference.clear();
        if (listener != null) {
            asyncResultWrapper = asyncResultWrapper.newState(ProcessState.DESTROY);
            listener.onAsyncRiskStateChange(asyncResultWrapper);
        }
        super.destroy();
    }


    @Override
    public void run() {
        List<String> result = RootDetectorPlus.checkAll(contextWeakReference.get());
        asyncResultWrapper.getResult().addAll(result);
        if (!result.isEmpty()) {
            asyncResultWrapper = asyncResultWrapper.inRisk(true);
            if (listener != null) {
                listener.onFindAsyncRisk(asyncResultWrapper);
            }
        }
        destroy();
    }
}
